//
//  R+Main.swift
//  KawanPrestamo
//
//  Created by Daiyi on 2024/4/20.
//

import DDBase
import KPHome
import KPUserCenter

public extension R.Router {
    static let mainRouterRun: Void = {
        DDRouteManager.shared.dd.handle(R.Router.loginUrl) { url, values, context in
          if let nav = DDAppearance.shared.keyWindow.rootViewController as? KPNavigationController {
              // 将所有的present控制器全部干掉
              nav.dismiss(animated: false)
              if nav.isLogin {
                  nav.popToRootViewController(animated: true)
                  return true
              }
          }
          
            let loginNav = KPNavigationController(rootViewController: KPLoginController());
            loginNav.isLogin = true
            DDAppearance.shared.keyWindow.rootViewController = loginNav
            return true
        }
        
        
        DDRouteManager.shared.dd.handle(R.Router.homeUrl) { url, values, context in
            if let nav = DDAppearance.shared.keyWindow.rootViewController as? KPNavigationController {
                // 将所有的present控制器全部干掉
                nav.dismiss(animated: false)
                if !nav.isLogin {
                    // 所在页面一直是home 的导航控制器
                    nav.popToRootViewController(animated: true)
                    return true
                }
            }
            let animated: Bool = context as? Bool ?? false
            
            let window = DDAppearance.shared.keyWindow
            var otherVC = window.rootViewController
            window.rootViewController = KPNavigationController(rootViewController: KPHomeController())
            if animated, let otherVC = otherVC {
                window.rootViewController?.view.addSubview(otherVC.view)
                UIView.animate(withDuration: 0.25, animations: {
                    otherVC.view.alpha = 0
                    otherVC.view.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
                }, completion: { isFinish in
                    otherVC.view.removeFromSuperview()
                })
            }
            
            return true
        }
    }()
}
